package com.yunc.common.utils;

import com.yunc.common.oss.QiniuCloudStorageService;
import com.yunc.common.properties.Pro;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.io.*;

/**
 * 利用二维码生成器
 *
 * @author taocongcong
 * @create 2017-09-04 9:37
 */
@EnableConfigurationProperties(Pro.class)
public class QrcodeUtil {

    private final static Pro pro = (Pro) SpringContextUtils.getBean("pro");
    private final static QiniuCloudStorageService qiniuCloudStorageService = (QiniuCloudStorageService) SpringContextUtils.getBean("qiniuCloudStorageService");

    /**
     * 只生成纯二维码
     */
    public static String qrcode(String url) throws Exception {
        OutputStream out = null;
        try {
            String newUrl = FilePathUtil.setFilePath();
            out = new FileOutputStream(newUrl);
            // 生成图片的绝对引用地址
            // String picUrl = StringUtils.replace(StringUtils.substringAfter(newUrl, pro.getBaseUploadURL()),"\\", "/");
            new SimpleQrcodeGenerator().generate(url).toStream(out);
            File file = new File(newUrl);
            InputStream inputStream = new FileInputStream(file);
            String upload = qiniuCloudStorageService.upload(inputStream);
            return upload;
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 生成带图片的二维码
     * 在线图片
     */
    public static String qrcode(String imgUrl, String url) throws Exception {
        OutputStream out = null;
        try {
            String newUrl = FilePathUtil.setFilePath();
            out = new FileOutputStream(newUrl);
            // 生成图片的绝对引用地址
            String picUrl = StringUtils.replace(StringUtils.substringAfter(newUrl, pro.getBaseUploadURL()),"\\", "/");
            new SimpleQrcodeGenerator().setRemoteLogo(imgUrl).generate(url).toStream(out);
            return pro.getBaseVisitURL()+picUrl;
        } finally {
            IOUtils.closeQuietly(out);
        }
    }
}
